import 'dart:developer';

import 'package:edu/utils/app_preferences.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:edu/constants/config.dart';

class CourseVideoPlayerWidgetLogic extends ChangeNotifier {
  final int id;
  late String videoUrl;
  late VideoPlayerController videoController;

  bool error = false;

  CourseVideoPlayerWidgetLogic({required this.id});

  void init() {
    videoUrl = '${Config.baseVideoUrl}/v1/course/video/$id';
    final url = Uri.parse(videoUrl);
    final token = AppPreferences.shared.userToken ?? '';
    videoController = VideoPlayerController.networkUrl(
      url,
      httpHeaders: {'authorization': 'Bearer $token'},
    );

    videoController.addListener(() {
      notifyListeners();
    });

    Future.delayed(Duration.zero, () {
      loadVideo();
    });
  }

  @override
  void dispose() {
    super.dispose();
    videoController.dispose();
  }

  void loadVideo() {
    videoController.initialize().catchError((e) {
      error = true;
      notifyListeners();
      log('loadVideo error: $e');
    });
  }
}
